﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CFE;
using CFEApp.Controllers;
using Microsoft.Win32;

namespace CFEApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

			ProjectController.Instance.CompilationComplete += Instance_CompilationComplete;

        }

		void Instance_CompilationComplete(object sender, ClosureProxy.CompilationCompleteEventArgs e)
		{

			var viewModel = this.ViewModel;

			viewModel.UpdateWorkItem(e);

			this.ViewModel = viewModel;
			

		}

		

		private void CloseCommand(object sender, RoutedEventArgs e)
		{
			this.Close();

		}

		private ViewModels.MainWindowViewModel ViewModel
		{
			get
			{
				ObjectDataProvider provider = (ObjectDataProvider)this.FindResource("projectDataSource");

				return (ViewModels.MainWindowViewModel)provider.ObjectInstance;
			}
			set
			{
				ObjectDataProvider provider = (ObjectDataProvider)this.FindResource("projectDataSource");
				provider.ObjectInstance = null;
				provider.ObjectInstance = value;
			}
		}


		private void OpenCommand(object sender, RoutedEventArgs e)
		{

			OpenFileDialog dlg = new OpenFileDialog();
			dlg.DefaultExt = ".cfe";
			dlg.Filter = "CFE Project File (.cfe)|*.cfe";

			bool? result = dlg.ShowDialog(this);

			if (result == true)
			{
				try
				{
					Project project = ProjectController.Instance.OpenProject(dlg.FileName);

					ViewModel = new ViewModels.MainWindowViewModel(project);

				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
			}

		}

		private void BuildCommand(object sender, RoutedEventArgs e)
		{
			var project = ProjectController.Instance.GetCurrentProject();
			if (project == null)
				return;
			ProjectController.Instance.Build();
		}


    }
}
